iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 25
1
自我挑戰組

今年我想陪著 30 天系列 第 25

今年我想陪著 30 天之 25

  • 分享至 

  • xImage
  •  

1436. Destination City

You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.

  • Example 1:
    Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
    Output: "Sao Paulo"
    Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".

  • Example 2:
    Input: paths = [["B","C"],["D","B"],["C","A"]]
    Output: "A"
    Explanation: All possible trips are:
    "D" -> "B" -> "C" -> "A".
    "B" -> "C" -> "A".
    "C" -> "A".
    "A".
    Clearly the destination city is "A".

  • Example 3:
    Input: paths = [["A","Z"]]
    Output: "Z"

var destCity = function(paths) {
    const targetCities = {};
    
    for (let i = 0; i < paths.length; i++) {
        targetCities[paths[i][0]] = targetCities[paths[i][0]] ? targetCities[paths[i][0]] - 1 : -1;
        targetCities[paths[i][1]] = targetCities[paths[i][1]] ? targetCities[paths[i][1]] + 1 : 1;
    }

    for (let key in targetCities) {
        if (targetCities[key] === 1) {
            return key;
        }
    }
};

上一篇
今年我想陪著 30 天之 24
下一篇
今年我想陪著 30 天之 26
系列文
今年我想陪著 30 天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言